import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/store/user'

// 定义需要登录才能访问的路由
const authRoutes = ['Profile']

const routes = [
  {
    path: '/auth',
    component: () => import('@/layouts/AuthLayout.vue'),
    children: [
      {
        path: 'login',
        name: 'Login',
        component: () => import('@/views/Auth/Login.vue'),
        meta: { title: '登录' }
      },
      {
        path: 'register',
        name: 'Register',
        component: () => import('@/views/Auth/Register.vue'),
        meta: { title: '注册' }
      }
    ]
  },
  {
    path: '/login',
    redirect: '/auth/login'
  },
  {
    path: '/register',
    redirect: '/auth/register'
  },
  {
    path: '/',
    component: () => import('@/layouts/MainLayout.vue'),
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('@/views/Home/index.vue'),
        meta: { title: '首页' }
      },
      {
        path: 'opportunity',
        name: 'Opportunity',
        component: () => import('@/views/Opportunity/index.vue'),
        meta: { title: '发现机会', requiresAuth: false }
      },
      {
        path: 'opportunity/:id',
        name: 'OpportunityDetail',
        component: () => import('@/views/Opportunity/OpportunityDetail.vue'),
        meta: { title: '机会详情', requiresAuth: false }
      },
      {
        path: 'share',
        name: 'Share',
        component: () => import('@/views/Share/index.vue'),
        meta: { title: '分享' }
      },
      {
        path: 'share/comment-wall',
        name: 'CommentWall',
        component: () => import('@/views/Share/CommentWall.vue'),
        meta: { title: '校园评论墙' }
      },
      {
        path: 'share/:id',
        name: 'ShareDetail',
        component: () => import('@/views/Share/Detail.vue'),
        meta: { title: '分享详情' }
      },
      {
        path: 'ai',
        name: 'AI',
        component: () => import('@/views/AI/index.vue'),
        meta: { title: 'AI助手' }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/Profile/index.vue'),
        meta: { title: '我的', requiresAuth: true }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    redirect: '/'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - HyperBoost` : 'HyperBoost'
  
  const userStore = useUserStore()
  
  // 检查是否需要登录权限
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    next({
      path: '/auth/login',
      query: { redirect: to.fullPath }
    })
  } else {
    next()
  }
})

export default router 